export const addTimeType = (editor) => {
  // 给component type 定义 model，定义属性、方法和事件
  const timerModel = editor.DomComponents.addType("timer", {
    model: {
      defaults: {
        tagName: "div",
        timer: 60, // seconds
        attributes: {
          'data-gjs-type':"timer",
        },
        script() {
          // 该脚本将在最终的 HTML 中打印
          const timerEl = this;
          let timer = timerEl.getAttribute("timer")
            ? parseInt(timerEl.getAttribute("timer"), 10)
            : 60;
          const interval = setInterval(() => {
            timerEl.innerHTML = timer;
            timer--;
            if (timer < 0) {
              clearInterval(interval);
              timerEl.innerHTML = "时间到!";
            }
          }, 1000);
        },
        // 在面板中显示计时器值
        badgeLabel() {
          return this.getAttributes().timer;
        },
      },
    },
  });

  // view用于定义在canvas里展现的UI
  const timerView = editor.DomComponents.getType("default").view.extend({
    events: {
      // 监听点击事件并更新定时器值
      click() {
        const model = this.model;
        const timer = model.getAttributes().timer;
        const newTimer = prompt("Enter the new timer value", timer);
        if (newTimer) {
          model.addAttributes({ timer: newTimer });
          model.trigger("change:script");
        }
      },
    },
  });

  editor.DomComponents.addType("timer", {
    model: timerModel,
    view: timerView,
  });

  editor.BlockManager.add("timer", {
    label: "计时器",
    category:'Basic',
    content: { type: "timer" },
    media:`<svg xmlns="http://www.w3.org/2000/svg" height="30" width="30" viewBox="0 0 384 512"><!--!Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path d="M0 24C0 10.7 10.7 0 24 0H360c13.3 0 24 10.7 24 24s-10.7 24-24 24h-8V67c0 40.3-16 79-44.5 107.5L225.9 256l81.5 81.5C336 366 352 404.7 352 445v19h8c13.3 0 24 10.7 24 24s-10.7 24-24 24H24c-13.3 0-24-10.7-24-24s10.7-24 24-24h8V445c0-40.3 16-79 44.5-107.5L158.1 256 76.5 174.5C48 146 32 107.3 32 67V48H24C10.7 48 0 37.3 0 24zM110.5 371.5c-3.9 3.9-7.5 8.1-10.7 12.5H284.2c-3.2-4.4-6.8-8.6-10.7-12.5L192 289.9l-81.5 81.5zM284.2 128C297 110.4 304 89 304 67V48H80V67c0 22.1 7 43.4 19.8 61H284.2z"/></svg>`
  });
};
